<script setup lang="ts" name="UserSocial">
import { SystemUserSocialTypeEnum } from '@/enums/systemEnums'
import { ProfileType } from '@/api/system/user/profile'
import { SocialApi } from '@/api/system/user/socialUser'

const props = defineProps({
  activeName: { type: String },
  userInfo: { type: Object as PropType<ProfileType> }
})

const { t } = useI18n() // 国际化
const message = useMessage()
const socialUsers = ref<any[]>([])

watch(
  () => props.userInfo,
  (v) => {
    if (v) {
      socialUsers.value = [] // 重置避免无限增长
      for (const i in SystemUserSocialTypeEnum) {
        const socialUser = { ...SystemUserSocialTypeEnum[i] }
        socialUsers.value.push(socialUser)
        if (props.userInfo?.socialUsers) {
          for (const j in props.userInfo.socialUsers) {
            if (socialUser.type === props.userInfo.socialUsers[j].type) {
              socialUser.openid = props.userInfo.socialUsers[j].openid
              break
            }
          }
        }
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)

const route = useRoute()
const emit = defineEmits<{
  (e: 'update:activeName', v: string): void
}>()
const bindSocial = () => {
  // 社交绑定
  const type = getUrlValue('type')
  const code = route.query.code
  const state = route.query.state
  if (!code) {
    return
  }
  SocialApi.bind(type, code, state).then(() => {
    message.success(t('profile.social', 'bindSuccess'))
    emit('update:activeName', 'userSocial')
  })
}

// 双层 encode 需要在回调后进行 decode
function getUrlValue(key: string): string {
  const url = new URL(decodeURIComponent(location.href))
  return url.searchParams.get(key) ?? ''
}

const bind = (row) => {
  // 双层 encode 解决钉钉回调 type 参数丢失的问题
  const redirectUri = location.origin + '/Profile?' + encodeURIComponent(`type=${row.type}`)
  // 进行跳转
  SocialApi.redirect(row.type, encodeURIComponent(redirectUri)).then((res) => {
    window.location.href = res
  })
}
const unbind = async (row) => {
  const res = await SocialApi.unbind(row.type, row.openid)
  if (res) {
    row.openid = undefined
  }
  message.success(t('profile.social', 'unbindSuccess'))
}

watch(
  () => route,
  () => {
    bindSocial()
  },
  {
    immediate: true
  }
)
</script>

<template>
  <el-table :data="socialUsers" :show-header="false">
    <el-table-column fixed="left" :title="t('common', 'index')" type="seq" width="60" />
    <el-table-column align="left" :label="t('profile.social', 'title')" width="120">
      <template #default="{ row }">
        <img :src="row.img" alt="" class="h-5 align-middle mt-10px" />
        <p class="m-0 mt-10px mb-10px">{{ row.title }}</p>
      </template>
    </el-table-column>
    <el-table-column align="center" :label="t('common', 'operate')">
      <template #default="{ row }">
        <template v-if="row.openid">
          {{ t('profile.social', 'bind') }}
          <CTextButton class="mr-5" style="vertical-align: 0;" :title="`(${t('profile.social.action', 'unbind')})`" type="primary" @click="unbind(row)" />
        </template>
        <template v-else>
          {{ t('profile.social', 'unbind') }}
          <CTextButton class="mr-5" style="vertical-align: 0;" :title="`(${t('profile.social.action', 'bind')})`" type="primary" @click="bind(row)" />
        </template>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped lang="scss"></style>
